import optparse
import re
import sys
import datetime

def join_version(version_list, separator, short):
  return separator.join(version_list[0:3 if short else 4])

def main(argv):
  parser = optparse.OptionParser()
  parser.add_option("--tune-file-path", dest="tune_file_path", help="Path to be tuned file.")
  parser.add_option("--product-version", dest="product_version", help="Version of product.")
  parser.add_option("--build-number", dest="build_number", help="Building number.")
  options, args = parser.parse_args(argv)

  if not options.product_version:
    print("You must specify --product-version parameter.")
    return 1

  product_version = options.product_version
  product_version_list = product_version.split('.')
  if len(product_version) <= 0 \
  or len(product_version_list) != 3 \
  or len(product_version_list[0]) != 4: # 2023.2.1
    print("Invalid product_version.")
    return 1

  build_number = options.build_number
  if not build_number or len(build_number) <=0:
    print("Invalid build_number.")
    return 1

  file_version_list = []
  file_version_list.append(product_version_list[0][-2:] + ("1" if datetime.date.today().month <= 6 else "2"))
  file_version_list.append("8")
  file_version_list.append(build_number)
  file_version_list.append("1")

  if not options.tune_file_path:
    print("You must specify --tune-file-path parameter.")
    return 1

  tune_file = open(options.tune_file_path, "r", encoding="utf-8")
  if not tune_file:
    print("Fail to open %s file for reading." % options.tune_file_path)
    return 1
  file_data = tune_file.read()
  tune_file.close()

  pattern_to_amend_list = [
    {"pattern": "VERSION = %s", "reg": "\\d+.\\d+.\\d+", "isMajor": False, "separator": '.', "short": True},
    {"pattern": "BIGVERSION = %s", "reg": "\\d+.\\d+.\\d+", "isMajor": True, "separator": '.', "short": True},
    {"pattern": "FILEVERSION %s", "reg": "\\d+,\\d+,\\d+,\\d+", "isMajor": False, "separator": ',', "short": False},
    {"pattern": "PRODUCTVERSION %s", "reg": "\\d+,\\d+,\\d+", "isMajor": True, "separator": ',', "short": True},
    {"pattern": "\"FileVersion\", \"%s\"", "reg": "\\d+.\\d+.\\d+.\\d+", "isMajor": False, "separator": '.', "short": False},
    {"pattern": "\"ProductVersion\", \"%s\"", "reg": "\\d+.\\d+.\\d+", "isMajor": True, "separator": '.', "short": True},
  ]

  for pattern in pattern_to_amend_list:
    file_data = re.sub(pattern["pattern"] % pattern["reg"], pattern["pattern"] % join_version( \
    product_version_list if pattern["isMajor"] else file_version_list, \
    pattern["separator"], pattern["short"]), file_data)

  tuned_file = open(options.tune_file_path, "w")
  if not tuned_file:
    print("Fail to open %s file for writing." % options.tune_file_path)
  tuned_file.write(file_data)
  tuned_file.close()
  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))